﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace IndirectX.Shaders
{
    public class ShaderParser
    {

        public static Dictionary<ChunkTag, Type> _chunkTypes;


        static ShaderParser()
        {
            _chunkTypes = new Dictionary<ChunkTag, Type>()
                {
                    { ChunkTag.RDEF, typeof(ResourceDefinitionChunk) },
                    { ChunkTag.SHDR, typeof(ShaderChunk) },
                    { ChunkTag.SHEX, typeof(ShaderChunk) },
                    { ChunkTag.STAT, typeof(StatisticsChunk) },
                    { ChunkTag.ISGN, typeof(InputShaderSignatureChunk) },
                    { ChunkTag.OSGN, typeof(OutputShaderSignatureChunk) },
                };
        }

        public static ShaderProgram Parse(DataStream dataStream)
        {
            ShaderProgram program = new ShaderProgram();
            program.Chunks = new List<Chunk>();

            var reader = new BinaryReader(dataStream);

            var magic = reader.ReadChars(4);
            var guid = new Guid(reader.ReadBytes(4 * 4));
            var version = reader.ReadUInt32();
            var totalLength = reader.ReadUInt32();

            var chunkCount = reader.ReadUInt32();
            var chunkOffsets = new uint[chunkCount];
            for (int i = 0; i < chunkCount; i++)
            {
                chunkOffsets[i] = reader.ReadUInt32();
            }

            for (int i = 0; i < chunkCount; i++)
            {
                reader.BaseStream.Seek(chunkOffsets[i], SeekOrigin.Begin);

                ChunkTag chunkType = reader.ReadUInt32();
                var chunkLength = reader.ReadUInt32();

                var chunk = (Chunk)Activator.CreateInstance(_chunkTypes[chunkType]);

                chunk.Parse(dataStream);
                program.Chunks.Add(chunk);

            }

       

            return program;
        }



    }
}
